iT邦幫忙

0

解LeetCode的學習筆記Day8_String to Integer(atoi)

LFI 2025-09-29 11:54:13113 瀏覽
  • 分享至 

  • xImage
  •  

今天是紀錄LeetCode解題的第八天

第八題題目:Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.
The algorithm for myAtoi(string s) is as follows:

  1. Whitespace: Ignore any leading whitespace (" ").
  2. Signedness: Determine the sign by checking if the next character is ' - ' or ' + ', assuming positivity if neither present.
  3. Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0.
  4. Rounding: If the integer is out of the 32-bit signed integer range [-2^31, 2^31 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -2^31, and integers greater than 2^31 - 1 should be rounded to 2^31 - 1.
    Return the integer as the final result.

實作myAtoi(string s)將字串轉換成32位元有號整數
演算法如下:

  1. 空格:忽略任何前導空格
  2. 符號:透過檢查下一個字元是否為' - ' 或 ' + '來確定符號,如果都不存在假設為正
  3. 轉換:讀取整數時跳過前導零,直到遇到非數字字元或達字串末尾,如果沒有讀取數字,則結果為 0
  4. 捨入:如果超出32位元有號整數範圍,小於-2^31應為-2^31,大於2^31 - 1應為2^31 - 1

程式碼如下

class Solution:
    def myAtoi(self, s: str) -> int:
        s = s.lstrip() #去掉前導空白
        if not s:
            return 0
        #處理正負號
        sign = 1
        if s[0] == '+' or s[0] == '-':
            if s[0] == '-':
                sign = -1
            s = s[1:]
        #開始讀數字
        num = 0
        for c in s:
            if not c.isdigit():
                break
            num = num * 10 + int(c)
            # 檢查是否超過範圍
            if sign == 1 and num >= 2**31 - 1:
                return 2**31 - 1
            if sign == -1 and num >= 2**31:
                return -2**31
        return sign * num

解題思路

  1. 去掉前導空白
  2. 檢查最前面是否有正負符號,' + ' → sign = 1,' - ' → sign = -1
  3. 一個一個讀入數字,如果遇到不是0~9的數字(表示這不是一個整數)就直接結束離開
  4. 是整數的話前一位元乘十放到左邊加當前位元
  5. 檢查是否超出範圍
  6. 最後把可以轉成整數的部分乘上符號回傳

圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言